package com.sgcc.pda.hzaidl;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;


import com.sgcc.pda.data.dao.SharepreferenceUtil;
import com.sgcc.pda.hzaidl.entity.CommonErrorBean;
import com.sgcc.pda.hzaidl.entity.RequestBean;
import com.sgcc.pda.hzaidl.entity.ResponseBean;
import com.sgcc.pda.hzaidl.error.HZErrorCode;
import com.sgcc.pda.hzaidl.impl.BackClipManager;

import com.sgcc.pda.tools.JsonUtils;

import com.sgcc.pda.tools.LogPrintUtils;
import com.sgcc.pda.util.PlatConstant;
import com.sgcc.platforminterface.PlatfInterfManager;





/**
 * Created by cj on 2019/12/2.
 * aidl操作类，外部调用统一使用此类。
 */
public class AIDLServiceImpl {

    private static final String TAG = "AIDLServiceImpl";
    private static final String SERVICE_ACTION = "com.sgcc.pda.hzaidl.service.mdrh";
    private static AIDLServiceImpl instance;
    private boolean isBind = false;

    /**
     * 统一AIDL接口
     */
    private IHZAidl aidlManager;

    /**
     * 绑定回调
     */
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            aidlManager = IHZAidl.Stub.asInterface(iBinder);
            isBind = aidlManager != null;
            LogPrintUtils.e("onServiceConnected: "+ (System.currentTimeMillis() - time));
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            aidlManager = null;
            isBind = false;
        }
    };

    public boolean isBind() {
        return isBind;
    }

    /**
     * 操作类单例获取接口
     *
     * @return 操作类实例
     */
    public static AIDLServiceImpl getInstance() {
        if (instance == null) {
            synchronized (AIDLServiceImpl.class) {
                if (instance == null) {
                    instance = new AIDLServiceImpl();
                }
            }
        }
        return instance;
    }


    /**
     * 原生应用绑定服务
     *
     * @param context: application上下文
     */
    public boolean bindService(Context context) {
        Intent intent = new Intent(SERVICE_ACTION);
        intent.setPackage("com.sgcc.pda.mdrh");
        boolean isBind = context.bindService(intent, connection, Context.BIND_AUTO_CREATE);
        time = System.currentTimeMillis();
        return isBind;
    }

    public long time = 0;
    /**
     * 原生应用绑定服务
     *
     * @param context:     application上下文
     * @param packageName: 服务所在包名
     */
    public boolean bindService(Context context, String packageName) {
        Intent intent = new Intent(SERVICE_ACTION);
        intent.setPackage(packageName);
        boolean isBind = context.bindService(intent, connection, Context.BIND_AUTO_CREATE);
        return isBind;
    }

    /**
     * 原生应用解绑服务
     *
     * @param context: application上下文
     */
    public void unbindService(Context context) {
        context.unbindService(connection);
        aidlManager = null;
        isBind = false;
    }

    /**
     * 插件化应用绑定Binder
     */
    public boolean bindBinder(IBinder binder) {
        if (isBind) {
            return isBind;
        } else {
            if (binder != null) {
                aidlManager = AIDLBinder.Stub.asInterface(binder);
                isBind = aidlManager != null;
            }

            return isBind;
        }
    }

    /**
     * 插件化应用解绑Binder
     */
    public void unbindBinder() {
        this.isBind = false;
        this.aidlManager = null;
    }

    public String post(String data, IHZAidlCallback callback) {
        return postBase(data, callback);
    }

    /**
     * 统一接口post方法。
     */
    public String postBase(String data, IHZAidlCallback callback) {
        if (aidlManager != null) {
            try {
                return aidlManager.post(data, callback);
            } catch (RemoteException e) {
                e.printStackTrace();
                callbackFail(callback, HZErrorCode.Error_1004);
            }
        } else {
            callbackFail(callback, HZErrorCode.Error_1001);
        }
        return null;
    }

    /**
     * 先判断是否需要通过蓝牙调用背夹
     * 若不需要返回true
     * 若需要，获取背夹蓝牙连接状态，若正常连接返回true，反之返回false
     *
     * @param data
     * @return
     */
    private boolean checkBackClipBtStatus(String data) {
        RequestBean bean = JsonUtils.toBean(data, RequestBean.class);
        //判断业务方法是否需要用背夹,目前暂定：mainCode为hardware且method为安全单元、电表（698、645、376）、电子封印
        if (bean.getMainCode().equals("hardware")
                && (bean.getMethodName().startsWith("unit")
                || bean.getMethodName().startsWith("meter")
                || bean.getMethodName().startsWith("seal"))) {
            return BackClipManager.getInstance().btIsConnect();
        } else {
            return true;
        }
    }

    interface ICheckBackClipStatus {
        /**
         * @param flag 0:蓝牙未连接，失败1:成功
         */
        void checkSuccess(int flag);
    }


    /**
     * 背夹蓝牙连接
     *
     * @param
     */
    private void connectBluetooth(final ICheckBackClipStatus iCheckBackClipStatus) {
        AlertDialog alertDialog = new AlertDialog.Builder(PlatfInterfManager.getInstance().getContext())
                .setTitle("蓝牙连接")
                .setMessage(String.format("当前蓝牙MAC地址：%s连接失败，请确定背夹蓝牙开启后重连或者重新更换蓝牙。",
                        SharepreferenceUtil.getBluetoothAddress(PlatfInterfManager.getInstance().getContext())))
                .setIcon(android.R.drawable.ic_dialog_info)
                .setPositiveButton("重新连接", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        BackClipManager.getInstance().btConnect(SharepreferenceUtil.
                                        getBluetoothAddress(PlatfInterfManager.getInstance().getContext()),
                                PlatConstant.ICommon.BACKCLIP_TIME_OUT_AUTO_CLOSE, new BackClipManager.BtConnectCallBack() {

                                    @Override
                                    public void connect(boolean connStatus, int code, String msg) {
                                        if (connStatus) {
                                            //连接成功走正常处理逻辑
                                            iCheckBackClipStatus.checkSuccess(1);
                                        } else {
                                            //连接失败,弹窗对话框提醒
                                            connectBluetooth(iCheckBackClipStatus);
                                        }
                                    }

                                    @Override
                                    public void disConnect() {

                                    }
                                });

                    }
                })

                .setNegativeButton("切换蓝牙", new DialogInterface.OnClickListener() {//添加取消
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        PlatfInterfManager.getInstance().getContext().sendBroadcast(new Intent(PlatConstant.ICommon.SYSTEM_EXIT_RESTART_ACTION));
                    }
                }).setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        iCheckBackClipStatus.checkSuccess(0);
                    }
                })
                .create();
        alertDialog.show();

    }

    private String callbackFail(IHZAidlCallback callback, HZErrorCode errorCode) {
        try {
            ResponseBean responseBean = new ResponseBean();
            responseBean.setRetCode(0);
            CommonErrorBean commonErrorBean = new CommonErrorBean(errorCode.getCode(), errorCode.getErrMessage());
            responseBean.setMsgJson(JsonUtils.toJson(commonErrorBean));
            String result = JsonUtils.toJson(responseBean);
            if (callback != null) {
                callback.callback(result);
            }
            return result;
        } catch (RemoteException e) {
            e.printStackTrace();
            LogPrintUtils.d("callbackFail", e);
        }
        return null;
    }

}
